<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

use SiteService;
use App\Models\Site;
use Illuminate\Contracts\Container\BindingResolutionException;
use ModuleService;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * 模块中间件/服务于前台
 * @package App\Http\Middleware
 */
class ModuleMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $this->init();
        $this->share();
        return $next($request);
    }

    /**
     * 系统初始化
     * @return void
     * @throws BindingResolutionException
     * @throws HttpException
     * @throws NotFoundHttpException
     */
    protected function init()
    {
        $site = request('site');
        $site = is_numeric($site) ? Site::find($site) : $site;
        $site = $site ?? SiteService::getByDomain();
        if (!($site instanceof Site)) {
            abort(404, '站点不存在');
        }
        define("SID", $site['id']);
        SiteService::cache($site);
        $this->module($site);
    }

    /**
     * 初始化模块
     * @param Site $site
     * @return void
     */
    protected function module(Site $site)
    {
        $module = ModuleService::getByDomain($site);

        if (!$module) {
            $module = $site->module;
        }
        if ($module) {
            ModuleService::cache($module);
        }
    }

    /**
     * 共享数据到前台
     * @return void
     * @throws BindingResolutionException
     */
    protected function share()
    {
        \View::share('site', site());
        \View::share('module', module());
    }
}
